<template>
  <a-layout-content>
    <back-bar-header text="消息中心"></back-bar-header>
    <a-layout
      class="message-container"
      :style="{ height: `${height - 188}px` }"
    >
      <a-layout-sider class="sider-menu">
        <a-menu
          v-model="noticeStatus"
          style="width: 200px;"
          mode="vertical"
          @click="handleStatusClick"
        >
          <a-menu-item :key="'all'">
            全部消息
          </a-menu-item>
          <a-menu-item :key="'unread'">
            未读消息
          </a-menu-item>
          <a-menu-item :key="'read'">
            已读消息
          </a-menu-item>
        </a-menu>
      </a-layout-sider>
      <a-layout-content class="message-content" style="background: #fff;">
        <div class="message-header">
          <a-checkbox
            style="padding-left: 2px; padding-right: 6px;"
            :checked="isAllChecked"
            @change="handleCheckAllChange"
          ></a-checkbox>
          <a-select
            v-model="noticeType"
            class="message-type"
            @change="handleTypeChange"
          >
            <a-select-option
              v-for="item in filterType"
              :key="item.type"
              :value="item.type"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-select
            v-show="noticeType === 4"
            v-model="projectId"
            class="message-project-name"
            style="width: 12%;"
            @change="handleProjectChange"
          >
            <a-select-option :key="'all-projects'" :value="-1">
              全部项目
            </a-select-option>
            <a-select-option
              v-for="project in projectList"
              :key="project.id"
              :value="project.id"
            >
              {{ project.name }}
            </a-select-option>
          </a-select>
          <span class="message-count">共{{ totalElements }}条</span>
          <a
            v-if="noticeStatus[0] != 'read'"
            class="message-action"
            @click="processAllNotice"
          >
            全部已读
          </a>
          <a
            v-if="hasNoticeChecked && noticeStatus[0] != 'read'"
            class="message-action"
            @click="processNotices"
          >
            设为已读
          </a>
          <a
            v-if="hasNoticeChecked"
            class="message-action"
            @click="deleteNotices"
          >
            删除
          </a>
        </div>
        <a-divider />
        <div>
          <a-list
            class="message-content-list"
            item-layout="horizontal"
            :style="{ maxHeight: `${height - 340}px` }"
            :data-source="noticeList"
          >
            <a-list-item slot="renderItem" slot-scope="item" class="list-item">
              <a-checkbox
                v-model="item.checked"
                style="padding-left: 6px; padding-right: 18px;"
              ></a-checkbox>
              <a-list-item-meta>
                <div
                  slot="title"
                  :class="
                    item.status === 1
                      ? 'notice-content-read'
                      : 'notice-content-unread'
                  "
                >
                  <b
                    v-for="(textItem, index) in splitMessageContent(
                      item.content
                    )"
                    :key="index + '-' + item.id"
                    :style="{
                      fontWeight: textItem[1] === 1 ? 'bold' : 'normal',
                    }"
                  >
                    {{ textItem[0] }}
                  </b>
                </div>
                <div
                  slot="title"
                  :class="
                    item.status === 1
                      ? 'notice-time-read'
                      : 'notice-time-unread'
                  "
                >
                  {{ moment(item.gmtModify).format('YYYY-MM-DD HH:mm:ss') }}
                </div>
                <a-avatar
                  slot="avatar"
                  style="background-color: #eaeafd;"
                  size="large"
                >
                  <a-icon-font slot="icon" class="avatar" type="icontouxiang" />
                </a-avatar>
              </a-list-item-meta>
              <!-- <router-link :to="`/project/${item.projectId}`"> -->
              <a-button
                v-if="item.projectId"
                class="notice-btn"
                size="small"
                @click="readMessage(item)"
                >查看</a-button
              >
              <!-- </router-link> -->
            </a-list-item>
          </a-list>
          <a-pagination
            v-model="currentPage"
            class="table-pagination"
            :total="totalElements"
            show-less-items
            show-size-changer
            show-quick-jumper
            @showSizeChange="onShowSizeChange"
            @change="onPageChange"
          />
        </div>
      </a-layout-content>
    </a-layout>
  </a-layout-content>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import MessageStore from '@/store/modules/message'
import moment from 'moment'
import BackBarHeader from '@/components/home/BackBarHeader.vue'

interface CheckboxList {
  [key: string]: boolean
}

@Component({
  components: {
    BackBarHeader,
  },
})
export default class MessageCenterView extends Vue {
  // 消息状态: 未读 - 0, 已读 - 1, 全部 - null
  private noticeStatus: Array<string> = ['all']

  // 消息类型: 全部类别 - 1, 系统消息 - 2,
  //         与我相关 - 3, 项目消息 - 4
  private noticeType: number = 1

  // 选中项目: 全部项目 - -1
  private projectId: number = -1

  // 分页
  private currentPage: number = 1
  private pageSize: number = 10

  private isAllChecked: boolean = false
  private height = document.body.clientHeight

  // 未读快照请求参数 & 已读快照请求参数
  private unreadPassData = {
    status: 0,
    pageNum: 1,
    pageSize: 10,
  }

  // 查询请求参数
  public get passData() {
    return {
      pageNum: this.currentPage,
      pageSize: this.pageSize,
      status: this.passStatus,
      filterType: this.noticeType,
      projectId: this.passProjectId,
    }
  }

  public async created() {
    await MessageStore.queryFilterType()
    await MessageStore.queryProjectList()
    await MessageStore.queryNoticeListInCenter(this.passData)
  }

  // 从 Message Store 中获取消息数据
  public get noticeList() {
    return MessageStore.noticeList
  }
  public get totalElements() {
    return MessageStore.totalElements
  }
  public get filterType() {
    return MessageStore.filterType
  }
  public get projectList() {
    return MessageStore.projectList
  }
  public get moment() {
    return moment
  }

  // 数据转换
  public get passStatus() {
    switch (this.noticeStatus[0]) {
      case 'all':
        return null
      case 'unread':
        return 0
      case 'read':
        return 1
      default:
        return null
    }
  }

  public get passProjectId() {
    return this.projectId === -1 ? null : this.projectId
  }

  public get hasNoticeChecked() {
    for (let index = 0; index < this.noticeList.length; index += 1) {
      if (this.noticeList[index].checked) {
        return true
      }
    }
    return false
  }

  // 分页
  public async onPageChange(page: any, size: any) {
    this.isAllChecked = false
    this.currentPage = page
    this.pageSize = size
    await MessageStore.queryNoticeListInCenter(this.passData)
  }
  public async onShowSizeChange(page: any, size: any) {
    this.isAllChecked = false
    this.currentPage = 1
    this.pageSize = size
    await MessageStore.queryNoticeListInCenter(this.passData)
  }

  // 选择 & 过滤消息
  public async handleStatusClick(item: any) {
    this.currentPage = 1
    this.noticeType = 1
    this.projectId = -1
    this.isAllChecked = false
    this.noticeStatus = [item.key]
    await MessageStore.queryProjectList()
    await MessageStore.queryNoticeListInCenter(this.passData)
  }

  public async handleTypeChange(value: number) {
    this.currentPage = 1
    this.noticeType = value
    this.projectId = -1
    this.isAllChecked = false
    await MessageStore.queryNoticeListInCenter(this.passData)
  }

  public async handleProjectChange(value: number) {
    this.currentPage = 1
    this.projectId = value
    this.isAllChecked = false
    await MessageStore.queryNoticeListInCenter(this.passData)
  }

  public handleCheckAllChange(event: any) {
    this.isAllChecked = event.target.checked
    this.noticeList.forEach(function changeChecked(item: any) {
      item.checked = event.target.checked
    })
  }

  // 查看消息
  public async readMessage(list: {
    id: string
    projectId: string
    status: number
  }) {
    if (list.status === 0) {
      // 未读消息设置为已读
      MessageStore.processNotice({ ids: [list.id] }).then(() => {
        // 更新消息中心页面消息队列
        MessageStore.queryNoticeListInCenter(this.passData)
        // 更新消息快捷入口消息队列
        MessageStore.queryNoticeListInShortcut(this.unreadPassData)
      })
    }
    if (list.projectId) {
      const routerUrl = this.$router.resolve(`/project/${list.projectId}/data`)
      window.open(routerUrl.href, '_blank')
    }
  }

  // 已读 & 删除消息
  public async processNotices() {
    this.isAllChecked = false
    const checkedNoticeList = this.noticeList
      .filter((item) => item.checked)
      .map((item) => item.id)
    await MessageStore.processNotice({ ids: checkedNoticeList })

    // 最后页消息均已读，回退一页
    if (
      checkedNoticeList.length === this.noticeList.length &&
      this.totalElements <= this.currentPage * this.pageSize
    ) {
      this.currentPage = Math.max(this.currentPage - 1, 1)
    }

    // 更新消息中心页面消息队列
    await MessageStore.queryNoticeListInCenter(this.passData)
    // 更新消息快捷入口消息队列
    await MessageStore.queryNoticeListInShortcut(this.unreadPassData)
  }

  public async processAllNotice() {
    this.isAllChecked = false

    // 全部消息已读
    await MessageStore.processAllNotice({})

    // 更新消息中心页面消息队列
    await MessageStore.queryNoticeListInCenter(this.passData)
    // 更新消息快捷入口消息队列
    await MessageStore.queryNoticeListInShortcut(this.unreadPassData)
  }

  public async deleteNotices() {
    this.isAllChecked = false
    const checkedNoticeList = this.noticeList
      .filter((item) => item.checked)
      .map((item) => item.id)
    await MessageStore.deleteNotice({ ids: checkedNoticeList })

    // 最后页消息均删除，回退一页
    if (
      checkedNoticeList.length === this.noticeList.length &&
      this.totalElements <= this.currentPage * this.pageSize
    ) {
      this.currentPage = Math.max(this.currentPage - 1, 1)
    }

    // 更新消息中心页面消息队列
    await MessageStore.queryNoticeListInCenter(this.passData)
    // 更新消息快捷入口消息队列
    await MessageStore.queryNoticeListInShortcut(this.unreadPassData)
  }

  // public async deleteAll() {
  //   this.isAllChecked = false
  //   await MessageStore.deleteAllNotice({ status: 1 })
  //   await MessageStore.queryNoticeListInCenter(this.passData)
  // }

  // 解析消息字符串
  public splitMessageContent(message: string) {
    const temporaryMessage = message.split('<b>').filter((item) => item !== '')
    const strongMessageContent: any[] = []
    temporaryMessage.forEach((item) => {
      if (item.includes('</b>')) {
        strongMessageContent.push([item.split('</b>')[0], 1])
        strongMessageContent.push([item.split('</b>')[1], 0])
      } else {
        strongMessageContent.push([item, 0])
      }
    })
    return strongMessageContent
  }
}
</script>

<style lang="less" scoped>
@import '@/constants';

.ant-layout-content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  margin: 13px 16px 16px;
}

.sider-menu {
  height: 100px;
  margin-top: 12px;
}

li {
  text-align: center;
}

.ant-menu-vertical > .ant-menu-item {
  color: #909198;
  font-size: 16px;
  font-weight: 400;
  height: 50px;
  letter-spacing: 1px;
  line-height: 50px;
  margin: 0;
  width: 200px;
}

.ant-menu-vertical .ant-menu-item:not(:last-child) {
  border-bottom: 1px solid #e9e9e9;
  margin: 0;
}

.ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected {
  background: #fff;
  border-left: 4px solid #6973ff;
  color: #373b52;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  letter-spacing: 1px;
  line-height: 50px;
  padding-left: 12px;
  width: 200px;
}

.ant-menu-item,
.ant-menu-submenu-title {
  transition: none;
}

.message-content {
  margin-right: 0;

  .message-content-list {
    overflow: scroll;

    &::-webkit-scrollbar {
      height: 6px;
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(144, 147, 153, 0.5);
      border-radius: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
      border-radius: 5px;
    }
  }
}

.message-header {
  height: 50px;
  line-height: 50px;
  padding-left: 24px;
}

.ant-divider-horizontal {
  margin: 0;
}

.ant-divider {
  margin: 0;
}

.message-status {
  color: #5d637e;
  font-size: 16px;
  font-weight: 500;
  height: 22px;
  letter-spacing: 1px;
  line-height: 22px;
  padding-right: 12px;
  width: 68px;
}

.message-count {
  color: #5d637e;
  font-size: 12px;
  font-weight: 400;
  height: 17px;
  letter-spacing: 1px;
  line-height: 17px;
  width: 35px;
}

.message-type {
  color: #5d637e;
  padding-left: 12px;
  padding-right: 12px;
}

.message-project-name {
  color: #5d637e;
  padding-right: 12px;
  width: 50px;
}

.message-action {
  color: #6973ff;
  float: right;
  font-size: 14px;
  font-weight: 400;
  height: 20px;
  letter-spacing: 1px;
  line-height: 50px;
  margin-right: 32px;
  right: 40px;
  //width: 60px;
}

.message-container {
  height: 100%;
}

.list-item {
  margin: 10px 0;
  padding: 10px 20px;
  text-align: left;
  width: 100%;
}

.table-pagination {
  padding: 20px;
  text-align: right;
  width: 100%;
}

.notice-btn {
  border: 1px solid #6771ff;
  color: #6973ff;
  font-size: 12px;
  font-weight: 400;
  height: 26px;
  margin-right: 10px;
  width: 50px;
}

.notice-time-unread {
  color: #5d637e;
  font-size: 12px;
  font-weight: 400;
  height: 16px;
  letter-spacing: 1px;
  line-height: 16px;
}

.notice-time-read {
  color: #93949b;
  font-size: 12px;
  font-weight: 400;
  height: 16px;
  letter-spacing: 1px;
  line-height: 16px;
}

.notice-content-unread {
  color: #5d637e;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 1px;
}

.notice-content-read {
  color: #93949b;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 1px;
}
</style>
